package com.example.edianzu.somur.module.health;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.edianzu.somur.MainActivity;
import com.example.edianzu.somur.R;
import com.example.edianzu.somur.api.APIRequest;
import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.api.constans.AppContents;
import com.example.edianzu.somur.api.manager.APIManager;
import com.example.edianzu.somur.module.health.adapter.HealthAdapter;
import com.example.edianzu.somur.module.health.bean.HealthPlan;
import com.example.edianzu.somur.module.mine.activity.ReportActivity;
import com.example.edianzu.somur.utils.content.L;
import com.example.edianzu.somur.utils.view.BaseFragment;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import static android.content.ContentValues.TAG;

/**
 * A simple {@link Fragment} subclass.
 */
public class HealthFragment extends BaseFragment {

    Unbinder unbinder;
    @BindView(R.id.fragment_health_title)
    AppCompatTextView fragmentHealthTitle;
    /*@BindView(R.id.fragment_health_content_0)
    TextView fragmentHealthContent0;
    @BindView(R.id.fragment_health_remark_0)
    TextView fragmentHealthRemark0;
    @BindView(R.id.fragment_health_name_0)
    TextView fragmentHealthName0;
    @BindView(R.id.fragment_health_content_1)
    TextView fragmentHealthContent1;
    @BindView(R.id.fragment_health_remark_1)
    TextView fragmentHealthRemark1;
    @BindView(R.id.fragment_health_name_1)
    TextView fragmentHealthName1;
    @BindView(R.id.fragment_health_LibearLayout_0)
    LinearLayout fragmentHealthLibearLayout0;
    @BindView(R.id.fragment_health_LibearLayout_1)
    LinearLayout fragmentHealthLibearLayout1;
    @BindView(R.id.fragment_health_content_2)
    TextView fragmentHealthContent2;
    @BindView(R.id.fragment_health_remark_2)
    TextView fragmentHealthRemark2;
    @BindView(R.id.fragment_health_name_2)
    TextView fragmentHealthName2;
    @BindView(R.id.fragment_health_LibearLayout_2)
    LinearLayout fragmentHealthLibearLayout2;*/
    @BindView(R.id.fragment_health_RecyclerView)
    RecyclerView fragmentHealthRecyclerView;
    @BindView(R.id.fragment_health_SwipeRefreshLayout)
    SwipeRefreshLayout fragmentHealthSwipeRefreshLayout;
    private int member_id;
    private LoginInfo loginInfo;
    private List<HealthPlan.DataBean.PushListBean> pushList;
    private HealthAdapter adapter;

    public HealthFragment() {
        // Required empty public constructor
    }

    //Fragment中的onAttach方法
    //通过强转成宿主activity，就可以获取到传递过来的数据
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        member_id = ((MainActivity) activity).getMember_id();
        loginInfo = ((MainActivity) activity).getLoginInfo();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        APIManager.getApiManagerInstance().getHealthList(new Observer<HealthPlan>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull HealthPlan healthPlan) {

                if (healthPlan.getStatus() == AppContents.STATUS) {

                    pushList = healthPlan.getData().getPushList();

                    L.d(TAG, "onNext: " + pushList.size());

                    adapter = new HealthAdapter(pushList);
                    fragmentHealthRecyclerView.setAdapter(adapter);
                    adapter.setOnItemClickListener(new HealthAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClickListener(View view, int position) {

                            Intent intent = new Intent(getContext(), ReportActivity.class);
                            intent.putExtra("url", APIRequest.HEALTHINFO_URL + "send_id=" + pushList.get(position).getId() + "&member_id=" + loginInfo.getData().getMember_id());
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        }, member_id + "");
    }

    @Override
    protected void initViewPagerFragment(List<String> title, List<Fragment> fragmentList) {

    }

    @Override
    protected boolean isLoadTopView() {
        return false;
    }

    @Override
    protected int setTopViewId() {
        return 0;
    }

    @Override
    protected int setLoadBottomViewId() {
        return 0;
    }

    @Override
    protected boolean isLoadBottomView() {
        return false;
    }

    //computeVerticalScrollExtent()是当前屏幕显示的区域高度，computeVerticalScrollOffset() 是当前屏幕之前滑过的距离，
// 而computeVerticalScrollRange()是整个View控件的高度
    private  boolean isRecyclerViewToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) {

            return false;
        }
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange()){

            return true;
        }else {
            return false;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_health, container, false);
        unbinder = ButterKnife.bind(this, view);
        
        initSwipeRefreshLayout();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        fragmentHealthRecyclerView.setLayoutManager(linearLayoutManager);
        fragmentHealthRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
//判断是否到达顶部
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                fragmentHealthSwipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
            }
        });


        if (pushList != null) {

            adapter = new HealthAdapter(pushList);
            fragmentHealthRecyclerView.setAdapter(adapter);
            adapter.setOnItemClickListener(new HealthAdapter.OnItemClickListener() {
                @Override
                public void onItemClickListener(View view, int position) {

                    Intent intent = new Intent(getContext(), ReportActivity.class);
                    intent.putExtra("url", APIRequest.HEALTHINFO_URL + "send_id=" + pushList.get(position).getId() + "&member_id=" + loginInfo.getData().getMember_id());
                    startActivity(intent);
                }
            });

        } else {


        }
        return view;
    }

    private void initSwipeRefreshLayout() {

        /*参数scale设置为true，则下拉过程，会自动缩放；参数end是下拉刷新的高度，也就是我们需要的参数，通过改变它的值，就能改变下拉刷新高度。*/
        fragmentHealthSwipeRefreshLayout.setProgressViewEndTarget (false,250);
        //设置初始时的大小
        fragmentHealthSwipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        fragmentHealthSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

//               清除适配器中的数据
                adapter.removeData();

//                fragmentHealthRecyclerView.setOnTouchListener(new View.OnTouchListener() {
//                            @Override
//                            public boolean onTouch(View v, MotionEvent event) {
//                                if (mIsRefreshing) {
//                                    return true;
//                                } else {
//                                    return false;
//                                }
//                            }
//                        }
//                );
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (fragmentHealthSwipeRefreshLayout.isRefreshing()) {

                            fragmentHealthSwipeRefreshLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    fragmentHealthSwipeRefreshLayout.setRefreshing(false);
                                }
                            });
                        }
                    }
                }, 1* 1000);

//                下拉完毕，加载更多数据
                APIManager.getApiManagerInstance().getHealthList(new Observer<HealthPlan>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull HealthPlan healthPlan) {

                        if (healthPlan.getStatus() == AppContents.STATUS) {

                            pushList = healthPlan.getData().getPushList();

                            L.d(TAG, "onNext: " + pushList.size());

//                            adapter = new HealthAdapter(pushList);
                            adapter.addData(pushList);
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                }, member_id + "");
            }


        });
        fragmentHealthSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.title));
//        设置进度条的背景颜色
        fragmentHealthSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.WHITE);
//        设置下拉多少距离开始刷新
        fragmentHealthSwipeRefreshLayout.setDistanceToTriggerSync(30);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
